<?php
require_once("../admin_config.inc.php");

class answer
{
    private $qid = null;
    private $table = null;
    
    function __construct($ques_id)
    {
        // create a connection to the database
        $db = connect_db();
        
        $this->qid = mysql_real_escape_string($ques_id);
        $this->table= "answers";
    }
    
    function getOptions()
    {
        $getopt = "select option_id,option_val from options where ques_id = {$this->qid}";
        
        $getopt_res = mysql_query($getopt);
        $data = array();
        
        while($getopt_row = mysql_fetch_object($getopt_res))
        {
            array_push($data,$getopt_res);
        }
        
        return $data;
    }
    
    function addAns($option_id)
    {
        if($this->checkAnsExists($option_id))
        {
            $data = array(  'ques_id' => $this->qid,
                            'option_id' => $opt_id );
            $key = implode("`,`",array_keys($data));
            $values = implode("','",$data);
            
            $ins_ans = vsprintf("insert into {$this->table}(`%s`) values('%s')",array($key,$values));
            
            $ins_res = mysql_query($ins_ans);
            return $ins_res;
        }
        else
            return false;
    }
    
    function editAns($old_option_id,$new_option_id)
    {
        if($this->checkAnsExists($old_option_id) && $this->checkNewAnsExists($new_option_id) )
        {
            $edit_query = "update {$this->table} set option_id = {$new_option_id} where option_id = {$old_option_id} and ques_id = $this->qid";
            $edit_res = mysql_query($edit_quer);
        
            if(mysql_num_rows($edit_res) == 1)
                return true;
            else
                return false;
        }
    }
    
    private function checkAnsExists($option_id)
    {
        $opt_id = mysql_real_escape_string($option_id);
        $check_ans = "select * from {$this->table} where ques_id = {$this->qid} and option_id = {$opt_id}";
        $check_res = mysql_query($check_ans);
        
        if(mysql_num_rows($check_res) == 1)
            return true;
        else
            return false;
    }
    
    private function checkNewAnsExists($option_id)
    {
        $opt_id = mysql_real_escape_string($option_id);
        $check_ans = "select * from options where ques_id = {$this->qid} and option_id = {$opt_id}";
        $check_res = mysql_query($check_ans);
        
        if(mysql_num_rows($check_res) == 1)
            return true;
        else
            return false;
    }
}
?>
